import React, { useState } from 'react';
import { Form, Input, Button, Card, Typography, message, Radio } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined, GiftOutlined } from '@ant-design/icons';
import { Link, useNavigate } from 'react-router-dom';
import { auth } from '../services';

const { Title } = Typography;

const Register = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const [loading, setLoading] = useState(false);
  const [registerType, setRegisterType] = useState('normal'); // 'normal' 或 'invite'
  const [form] = Form.useForm();
  const navigate = useNavigate();

  const onFinish = async (values) => {
    setLoading(true);

    try {
      // 准备提交数据
      const { username, password, email, inviteCode } = values;

      // 构建注册请求数据
      const userData = {
        username,
        password,
        email,
        isInvited: registerType === 'invite', // 对应后端 isInvited 参数
        code: registerType === 'invite' ? inviteCode : undefined // 对应后端 code 参数
      };

      // 直接调用注册接口
      const response = await auth.register(userData);

      if (response.code === 200) {
        messageApi.success('注册成功！请登录');
        // 延迟3秒后跳转到登录页面
        setTimeout(() => {
          navigate('/login');
        }, 3000); // 3000毫秒 = 3秒
      } else {
        messageApi.error(response.message || '注册失败');
      }
    } catch (error) {
      // 根据错误码处理不同错误情况
      if (error.code === 404) {
        messageApi.error('邀请码不存在，请检查输入');
      } else if (error.code === 409) {
        messageApi.error('邀请码已被使用，请获取新的邀请码');
      } else if (error.code === 422) {
        messageApi.error('邮箱域名与邀请码创建者域名不匹配');
      } else if (error.code === 406) {
        messageApi.error('用户名已存在，请更换用户名');
      } else {
        messageApi.error(error.message || '注册失败，请检查网络连接');
      }
      console.error('注册出错:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleRegisterTypeChange = (e) => {
    setRegisterType(e.target.value);
    // 当切换注册类型时，重置表单中的邀请码字段
    if (e.target.value === 'normal') {
      form.setFieldsValue({ inviteCode: undefined });
    }
  };

  return (
    <div className="register-container">
      {contextHolder}
      <Card className="register-card">
        <div style={{ textAlign: 'center', marginBottom: 24 }}>
          <Title level={2} style={{ color: '#001529' }}>星域 PT</Title>
          <Title level={4} style={{ color: '#8c8c8c' }}>加入我们的星际社区</Title>
          <p style={{ color: '#8c8c8c' }}>本站仅对教育网用户开放注册，请使用.edu.cn结尾的邮箱</p>
          {registerType === 'invite' && (
            <p style={{ color: '#ff4d4f' }}>注意：邀请码只能被同一教育机构的用户使用（如@bjtu.edu.cn邀请码只能给@bjtu.edu.cn邮箱用户使用）</p>
          )}
        </div>

        <Form
          form={form}
          name="register"
          className="register-form"
          onFinish={onFinish}
          initialValues={{ registerType: 'normal' }}
        >
          <Form.Item name="registerType">
            <Radio.Group onChange={handleRegisterTypeChange} value={registerType}>
              <Radio value="normal">普通注册</Radio>
              <Radio value="invite">邀请注册</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            name="username"
            rules={[
              { required: true, message: '请输入用户名！' },
              { min: 3, message: '用户名至少3个字符' }
            ]}
          >
            <Input prefix={<UserOutlined />} placeholder="用户名" size="large" />
          </Form.Item>

          <Form.Item
            name="email"
            rules={[
              { required: true, message: '请输入邮箱！' },
              { type: 'email', message: '请输入有效的邮箱地址' },
              {
                validator: (_, value) => {
                  if (!value || value.toLowerCase().endsWith('.edu.cn')) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('必须使用以.edu.cn结尾的教育邮箱'));
                }
              }
            ]}
            help="请使用教育邮箱（以.edu.cn结尾）"
          >
            <Input prefix={<MailOutlined />} placeholder="教育邮箱" size="large" />
          </Form.Item>

          {registerType === 'invite' && (
            <Form.Item
              name="inviteCode"
              rules={[
                { required: true, message: '请输入邀请码！' },
                { min: 6, message: '邀请码格式不正确' }
              ]}
            >
              <Input prefix={<GiftOutlined />} placeholder="邀请码" size="large" />
            </Form.Item>
          )}

          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码！' },
              { min: 6, message: '密码至少6个字符' }
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
              size="large"
            />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            dependencies={['password']}
            rules={[
              { required: true, message: '请确认密码！' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致！'));
                },
              }),
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="确认密码"
              size="large"
            />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" className="login-form-button" loading={loading} size="large">
              注册
            </Button>
            <div style={{ marginTop: 16, textAlign: 'center' }}>
              已有账号？<Link to="/login">立即登录</Link>
            </div>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Register; 